package com.erpanderp.wam.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import com.erpanderp.wam.util.model.entity.WAMEmail;
import com.erpanderp.wam.util.model.service.WAMEmailDAO;

public class EmailUtil {
	private WAMEmail wamEmail;
	private InternetAddress senderInternetAddress;
	private InternetAddress[] recieverInternetAddresses;
	private InternetAddress[] ccInternetAddresses;
	private String subject;
	private String messageText;
	private FileDataSource fileDataSource;

	public EmailUtil() {
		wamEmail = new WAMEmail();
	}

	public void setSenderEmail(String senderEmail, String personal) {
		wamEmail.setSenderEmail(senderEmail);
		try {
			senderInternetAddress = new InternetAddress(senderEmail, personal);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public void setRecieverAddresses(String[] strings) {
		StringBuilder result = new StringBuilder();
		recieverInternetAddresses = new InternetAddress[strings.length];
		int counter = 0;
		for (String string : strings) {
			try {
				recieverInternetAddresses[counter] = new InternetAddress(string);				
			} catch (AddressException e) {
				e.printStackTrace();
			}

			result.append(string);
			result.append(",");
			counter++;
		}
		wamEmail.setRecieverEmails(result.substring(0, result.length() - 1));
	}

	public void setCCAddresses(String[] strings) {
		StringBuilder result = new StringBuilder();
		ccInternetAddresses = new InternetAddress[strings.length];
		int counter = 0;
		for (String string : strings) {
			try {
				ccInternetAddresses[counter] = new InternetAddress(string);			
			} catch (AddressException e) {
				e.printStackTrace();
			}

			result.append(string);
			result.append(",");
			counter++;
		}
		wamEmail.setCcEmails(result.substring(0, result.length() - 1));
	}

	public void setSubject(String subject) {
		wamEmail.setSubject(subject);
		this.subject = subject;
	}

	public void setMessage(String message) {
		wamEmail.setMessageText(message);
		messageText = message;
	}

	public void setFile(File file) {
		fileDataSource = new FileDataSource(file) {
			@Override
			public String getContentType() {
				return "application/octet-stream";
			}
		};
		wamEmail.setFileName(file.getName());
	}

	public String processAndSendEmail(){
		Date now = new Date();
		String MESSAGE = "";
		WAMEmailDAO wamEmailDAO = new WAMEmailDAO();
		setSenderEmail("ezone@erpanderp.com", "WAM");
		if(sendEmail()){
			wamEmail.setEmailStatus("SENT");
			wamEmail.setCreatedBy(CommonLookup.CREATEDBY_DEVELOPER_TEXT);
			wamEmail.setEmailDate(now);
			wamEmail.setEmailPurpose("DUMMY");
			wamEmail.setStatus(CommonLookup.STATUS_ACTIVE);
			wamEmail.setCreateDate(now);
			if(wamEmailDAO.recordWAMEmail(wamEmail))
				MESSAGE = CommonLookup.EMAIL_SENT_AND_RECORDED;
			else
				MESSAGE = CommonLookup.EMAIL_SENT_AND_NOT_RECORDED;
		}else{
			wamEmail.setEmailStatus("FAILED");
			if(wamEmailDAO.recordWAMEmail(wamEmail))
				MESSAGE = CommonLookup.EMAIL_FAILED_AND_RECORDED;
			else
				MESSAGE = CommonLookup.EMAIL_FAILED_AND_NOT_RECORDED;
		}
		wamEmail.setEmailStatus(MESSAGE);
		wamEmailDAO.updateWAMEmail(wamEmail);
		
		return MESSAGE;
	}
	
	private boolean sendEmail() {
		String HOST = "smtp.gmail.com";
		String USERNAME = "ezone@erpanderp.com";
		String PASSWORD = "ezone@erpanderp";
		String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
		boolean EMAIL_SENT;
		boolean SESSION_DEBUG = true;

		Properties props = System.getProperties();
		props.put("mail.host", HOST);
		props.put("mail.transport.protocol", "smtp");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.", "true");
		props.put("mail.smtp.port", "465");
		props.put("mail.smtp.socketFactory.fallback", "false");
		props.put("mail.smtp.socketFactory.class", SSL_FACTORY);

		Session mailSession = Session.getDefaultInstance(props, null);
		mailSession.setDebug(SESSION_DEBUG);

		Message msg = new MimeMessage(mailSession);
		try {
			msg.setFrom(senderInternetAddress);

			msg.setRecipients(Message.RecipientType.TO, recieverInternetAddresses);
			msg.setRecipients(Message.RecipientType.CC, ccInternetAddresses);

			msg.setSubject(subject);
			msg.setContent(messageText, "text/html");
			setSenderEmail("ezone@erpanderp.com", "WAM");
			MimeBodyPart messagePart = new MimeBodyPart();
			messagePart.setText(messageText, "ISO-8859-1", "html");
			MimeBodyPart attachmentPart = null;
			Multipart multipart = new MimeMultipart();
			multipart.addBodyPart(messagePart);

			if(fileDataSource != null){
				attachmentPart = new MimeBodyPart();

				attachmentPart.setDataHandler(new DataHandler(fileDataSource));
				attachmentPart.setFileName(wamEmail.getFileName());
				multipart.addBodyPart(attachmentPart);	
			}
			
			msg.setContent(multipart);
			Transport transport = mailSession.getTransport("smtp");
			transport.connect(HOST, USERNAME, PASSWORD);
			transport.sendMessage(msg, msg.getAllRecipients());

			transport.close();
			EMAIL_SENT = true;
			System.out.println("EMAIL SENT");
			return EMAIL_SENT;
		} catch (MessagingException e) {
			e.printStackTrace();
			EMAIL_SENT = false;
			System.out.println("FAILED: " + e.getMessage());
			return EMAIL_SENT;
		}
	}

	public WAMEmail getWamEmail() {
		return wamEmail;
	}

	public void setWamEmail(WAMEmail wamEmail) {
		this.wamEmail = wamEmail;
	}

	public static void main(String a[]){
		EmailUtil emailUtil = new EmailUtil();
		String[] to = {"ramakrishna.t@erpanderp.com", "dayasankar.s@erpanderp.com"};
		String[] cc = {"dayasankar@ymail.com", "daia.yum@gmail.com"};
		emailUtil.setRecieverAddresses(to);
		emailUtil.setCCAddresses(cc);
		
		
		String messageString = "Dear Daia" +
				",<br />" +
				"<h3>New Travel Request Details</h3>" +
		        "<table style='border: 1px solid #d9d9d9;'>" +
		        "<tr> <td>Employee Code </td><td> : </td><td>" + "E50051" + " </td></tr>" +
		        "<tr> <td>Employee name</td><td> : </td> <td>" + "Ramakrishna Thota" + " </td></tr>" +
		        "<tr> <td>Travel Request Code</td><td> : </td> <td>" + "TR-D-E50051-12" + "</td></tr>" +
		        "<tr> <td>Travel Start Date</td><td> : </td> <td>" + "May-21-2012" + "</td></tr>" +
		        "<tr> <td>Travel Return Date</td><td> : </td> <td>" + "Jun-12-1212" + "</td></tr>" +
		        "</table><br/>"+								
		        "<a style='color:#FF9933;font-weight: bold;' href=\""+
		        "" + "\">" + "Please click here to approve/reject travel request" + "</a /><br />"+
				"(Employees who are in Hyderabad office)"+"<br /><br />"+
				"<a style='color:#FF9933;font-weight: bold;' href=\""+
				"" + "\">" + "Please click here to approve/reject travel request" + "</a /><br />"+
				"(out side Hyderabad office)"+"<br /><br />"+
				
				"Thanks & Regards, <br />"+CommonLookup.WAM_DEVTEAM_SIGNATURE;;
		
		emailUtil.setMessage(messageString);
		
		
		emailUtil.setSenderEmail("podquick@erpanderp.com", "WAM - Dev Team");
		emailUtil.setSubject("WAM - Test email");
		System.out.println(emailUtil.processAndSendEmail());
	}
}
